<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="springboot-step-by-step,">










<meta name="description" content="本文为《一步一步学习Spring Boot 2》的第七章的学习笔记，主要内容为Spring Boot集成Redis缓存 本书博客地址：https://blog.csdn.net/huangwenyi1010?t=1 源代码地址：https://gitee.com/aiolos123/springboot-step-by-step">
<meta name="keywords" content="springboot-step-by-step">
<meta property="og:type" content="article">
<meta property="og:title" content="【第七章】一步一步学习SpringBoot2——集成Redis缓存">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/07/19/spring-boot-step-by-step-four/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为《一步一步学习Spring Boot 2》的第七章的学习笔记，主要内容为Spring Boot集成Redis缓存 本书博客地址：https://blog.csdn.net/huangwenyi1010?t=1 源代码地址：https://gitee.com/aiolos123/springboot-step-by-step">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725062619906.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725062716469.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725062833580.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725062910589.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725062952446.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725063733738.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725064136765.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725155516236.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725155801615.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190725160223417.jpg">
<meta property="og:updated_time" content="2019-07-25T08:11:40.174Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【第七章】一步一步学习SpringBoot2——集成Redis缓存">
<meta name="twitter:description" content="本文为《一步一步学习Spring Boot 2》的第七章的学习笔记，主要内容为Spring Boot集成Redis缓存 本书博客地址：https://blog.csdn.net/huangwenyi1010?t=1 源代码地址：https://gitee.com/aiolos123/springboot-step-by-step">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20190725062619906.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/07/19/spring-boot-step-by-step-four/">





  <title>【第七章】一步一步学习SpringBoot2——集成Redis缓存 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/07/19/spring-boot-step-by-step-four/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【第七章】一步一步学习SpringBoot2——集成Redis缓存</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-19T10:24:24+08:00">
                2019-07-19
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Springboot/" itemprop="url" rel="index">
                    <span itemprop="name">Springboot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为《一步一步学习Spring Boot 2》的第七章的学习笔记，主要内容为Spring Boot集成Redis缓存</p>
<p>本书博客地址：<a href="https://blog.csdn.net/huangwenyi1010?t=1" target="_blank" rel="noopener">https://blog.csdn.net/huangwenyi1010?t=1</a></p>
<p>源代码地址：<a href="https://gitee.com/aiolos123/springboot-step-by-step" target="_blank" rel="noopener">https://gitee.com/aiolos123/springboot-step-by-step</a></p>
<a id="more"></a>
<h1 id="注意事项"><a href="#注意事项" class="headerlink" title="注意事项"></a>注意事项</h1><ol>
<li>虽然引入Redis缓存用户数据可以提高访问性能，但是带来的代码复杂度也是可想而知的。所以在以后的工作中，在性能和代码复杂度的权衡下，大家要根据具体的业务场景去加以选择，不可滥用缓存。</li>
</ol>
<h1 id="Redis简介"><a href="#Redis简介" class="headerlink" title="Redis简介"></a>Redis简介</h1><blockquote>
<p>Redis是一个基于内存的、单线程、高性能key-value型数据库，读写性能优异。和Memcached缓存相比，Redis支持丰富的数据类型，包括string(字符串)、list(链表)、set(集合)、zset(sorted set有序集合)和hash（哈希类型）。因此Redis在企业中被广泛使用。</p>
</blockquote>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><ol>
<li>下载Redis的Window版本<br>Redis项目本身是不支持Window，但是Microsoft开放技术小组开发和维护这个Windows端口针对Win64。所以我们可以在网络上下载Redis的Window版本：<br>下载地址：<a href="https://github.com/MicrosoftArchive/redis/tags" target="_blank" rel="noopener">https://github.com/MicrosoftArchive/redis/tags</a></li>
</ol>
<p><img src="/blog/images/20190725062619906.jpg" alt="下载Redis的Window版本"></p>
<ol start="2">
<li>安装过程见：<a href="http://www.runoob.com/note/36178" target="_blank" rel="noopener">http://www.runoob.com/note/36178</a><br><img src="/blog/images/20190725062716469.jpg" alt="安装过程"></li>
</ol>
<h2 id="启动Redis服务"><a href="#启动Redis服务" class="headerlink" title="启动Redis服务"></a>启动Redis服务</h2><p>启动Redis服务后，在 cmd 窗口进入Redis的安装路径的根目录输入命令 redis-server.exe redis.windows.conf，出现下图证明 Redis 服务启动成功：<br><img src="/blog/images/20190725062833580.jpg" alt="启动Redis服务"></p>
<p>如果出现如下错误，表示Redis服务已经启动：<br><img src="/blog/images/20190725062910589.jpg" alt="启动Redis服务"></p>
<h2 id="使用Redis"><a href="#使用Redis" class="headerlink" title="使用Redis"></a>使用Redis</h2><p>在 Redis 的安装根目录下找到 redis-cli.exe 文件，双击启动<br><img src="/blog/images/20190725062952446.jpg" alt="使用Redis"></p>
<h2 id="操作Redis五种数据类型"><a href="#操作Redis五种数据类型" class="headerlink" title="操作Redis五种数据类型"></a>操作Redis五种数据类型</h2><p>本文中不再赘述，详见：<a href="https://blog.csdn.net/huangwenyi1010/article/details/82821328" target="_blank" rel="noopener">https://blog.csdn.net/huangwenyi1010/article/details/82821328</a></p>
<h2 id="Redis-Client"><a href="#Redis-Client" class="headerlink" title="Redis Client"></a>Redis Client</h2><p>RedisClient：redis可视化客户端工具。通过该客户端，我们可以清楚的查看Redis数据库中存放的数据情况，同时可以在客户端中对数据进行增删改查等操作，方便使用<br>下载地址：<a href="https://github.com/caoxinyu/RedisClient" target="_blank" rel="noopener">https://github.com/caoxinyu/RedisClient</a></p>
<h1 id="Spring-Boot集成Redis缓存"><a href="#Spring-Boot集成Redis缓存" class="headerlink" title="Spring Boot集成Redis缓存"></a>Spring Boot集成Redis缓存</h1><blockquote>
<p>在Spring Boot中提供了强大的基于注解的缓存支持，配置了多个CacheManager的实现，我们可以根据具体的项目要求使用相应的缓存技术。在不添加任何额外配置的情况下，Spring Boot默认使用SimpleCacheConfiguration，考虑到Redis缓存在企业中被广泛使用，故选择用Redis缓存来进行讲解。</p>
</blockquote>
<ol>
<li><p>在pom.xml文件中引入所需的Redis依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--Redis依赖--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>在application.properties文件中添加缓存配置</p>
<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">### Redis的配置 ##################################</span><br><span class="line">### 默认redis数据库为db0</span><br><span class="line">spring.redis.database=<span class="number">0</span></span><br><span class="line">### 服务器地址，默认为localhost</span><br><span class="line">spring.redis.host=localhost</span><br><span class="line">### 端口，默认为<span class="number">6379</span></span><br><span class="line">spring.redis.port=<span class="number">6379</span></span><br><span class="line">### redis密码默认为空</span><br><span class="line">spring.redis.password=</span><br></pre></td></tr></table></figure>
</li>
<li><p>测试Redis集成成功<br><img src="/blog/images/20190725063733738.jpg" alt="测试Redis集成成功"></p>
</li>
</ol>
<blockquote>
<p>RedisTemplate和StringRedisTemplate都是Spring Data Redis为我们提供的两个模板类用来对Redis数据进行操作。 </p>
</blockquote>
<blockquote>
<p>RedisTemplate和StringRedisTemplate除了提供opsForValue方法用来操作简单属性数据之外，还提供了以下其它主要数据访问方法：<br>1）opsForList：操作含有list的数据。<br>2）opsForSet：操作含有set的数据。<br>3）opsForZSet：操作含有ZSet（有序set）的数据。<br>4）opsForHash：操作含有hash的数据。</p>
</blockquote>
<blockquote>
<p>当我们的数据存放到Redis的时候，键（key）和值（value）都是通过Spring提供的Serializer序列化到Redis数据库的。RedisTemplate默认使用JdkSerializationRedisSerializer，而StringRedisTemplate默认使用StringRedisSerializer。</p>
</blockquote>
<ol start="4">
<li>在Redis Client客户端中查看结果<br>运行完单元测试用例，除了可以在控制台查看打印结果信息和在redis客户端查看数据之外，我们还可以使用Redis Client客户端工具查看Redis缓存数据库中的数据。<br><img src="/blog/images/20190725064136765.jpg" alt="Redis Client客户端中查看结果"></li>
</ol>
<h1 id="Redis缓存在Spring-Boot中使用"><a href="#Redis缓存在Spring-Boot中使用" class="headerlink" title="Redis缓存在Spring Boot中使用"></a>Redis缓存在Spring Boot中使用</h1><h2 id="在监听器Listener中缓存用户数据"><a href="#在监听器Listener中缓存用户数据" class="headerlink" title="在监听器Listener中缓存用户数据"></a>在监听器Listener中缓存用户数据</h2><p>在上一篇文章中，已经简单的开发好AyUserListener监听器类，并在上下文启动时候打印信息。</p>
<p>在本文中，我们要在上下文初始化的方法中，加载数据库中的所有用户数据，并存放到Redis缓存中。之所以要把用户数据存放到缓存中，是因为用户的数据属于变动不大的数据，适合存放到缓存中，在应用需要获取用户数据时，可以直接到Redis缓存中获取，不用到数据库中获取数据库连接查询数据，提高数据的访问速度。</p>
<p>具体代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 自定义监听器</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 在ServletContext上下文初始化时将用户数据缓存到Redis中</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@WebListener</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AyUserListener</span> <span class="keyword">implements</span> <span class="title">ServletContextListener</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    Logger logger = LogManager.getLogger();</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> RedisTemplate redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> IAyUserService iAyUserService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//存放到Redis中的用户数据的变量名</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String REDIS_ALL_USER = <span class="string">"ALL_USER_LIST"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">contextInitialized</span><span class="params">(ServletContextEvent servletContextEvent)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//查询数据库所有用户</span></span><br><span class="line">        List&lt;AyUser&gt; ayUserList = iAyUserService.findAll();</span><br><span class="line">        <span class="comment">//清除缓存中的用户数据</span></span><br><span class="line">        redisTemplate.delete(REDIS_ALL_USER);</span><br><span class="line">        <span class="comment">//将用户数据插入到Redis中</span></span><br><span class="line">        redisTemplate.opsForList().leftPushAll(REDIS_ALL_USER,ayUserList);</span><br><span class="line">        <span class="comment">//在真实项目中，不会在初始化时就从缓存中查询所有用户数据，需注释掉</span></span><br><span class="line">        List&lt;AyUser&gt; queryUserList = redisTemplate.opsForList().range(REDIS_ALL_USER,<span class="number">0</span>,-<span class="number">1</span>);</span><br><span class="line">        <span class="comment">//System.out.println("Redis缓存中的用户总数:"+queryUserList.size());</span></span><br><span class="line">        logger.info(<span class="string">"Redis缓存中的用户总数:"</span>+queryUserList.size());</span><br><span class="line">        <span class="comment">//System.out.println("ServletContext上下文初始化");</span></span><br><span class="line">        logger.info(<span class="string">"ServletContext上下文初始化"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">contextDestroyed</span><span class="params">(ServletContextEvent servletContextEvent)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//System.out.println("ServletContext上下文销毁");</span></span><br><span class="line">        logger.info(<span class="string">"ServletContext上下文销毁"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>说明：</p>
<ol>
<li><p>redisTemplate.opsForList().leftPushAll()：查询缓存中所有的用户数据，REDIS_ALL_USER键若不存在，会创建该键及与其关联的List，之后再将参数中的ayUserList从左到右依次插入。</p>
</li>
<li><p>redisTemplate.opsForList().range()：取Redis缓存中的全部元素，其中0表示第一个元素，-1表示最后一个元素。</p>
</li>
<li><p>当数据存放到Redis中时，键和值需要通过Spring提供的Serializer进行序列化，但如果POJO未实现Serializable接口，则会报如下错误：</p>
</li>
</ol>
<p><img src="/blog/images/20190725155516236.jpg" alt="POJO未实现Serializable接口"></p>
<ol start="4">
<li>上述错误原因：</li>
</ol>
<blockquote>
<p>当数据存放到Redis的时候，键（key）和值（value）都是通过Spring提供的Serializer序列化到数据库，<br>RedisTemplate默认使用JdkSerializationRedisSerializer，而StringRedisTemplate默认使用StringRedisSerializer。</p>
</blockquote>
<p>解决方案： 让实体类AyUser实现序列化接口Serializable，具体代码如下：</p>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AyUser</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">4125096758372084309</span>L;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//省略其他代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>重新启动项目，Redis缓存就可以正常使用了。<br><img src="/blog/images/20190725155801615.jpg" alt="Redis缓存就可以正常使用"></p>
<h2 id="更新缓存数据"><a href="#更新缓存数据" class="headerlink" title="更新缓存数据"></a>更新缓存数据</h2><p>将所有用户数据在项目启动时就加载到缓存中，提供了数据访问速度，但我们还需要修改AyUserServiceImpl中的接口方法，因为它们现在还是直接从数据库中查询的数据————需要改为：</p>
<pre><code>1. 首先从Redis中查询，
2. 如果Redis中没有，再去数据库中查询，
3. 将查询结果更新到Redis中</code></pre><p>这样方便以后查询。</p>
<p><del>对方法findById进行修改AyUserServiceImpl修改的代码如下：</del> (实际开发中，更多是使用注解实现数据缓存，见本文的下一节)<br><img src="/blog/images/20190725160223417.jpg" alt="Redis缓存查询"></p>
<p>所有更新缓存数据的查询的思路都是如上所述的。</p>
<h1 id="注解实现Redis数据缓存"><a href="#注解实现Redis数据缓存" class="headerlink" title="注解实现Redis数据缓存"></a>注解实现Redis数据缓存</h1><p>上一节已经实现了在Redis中将数据缓存的功能，但增加了代码的复杂度。而通过注解的方式实现数据缓存功能，只需要三个注解即可。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/springboot-step-by-step/" rel="tag"># springboot-step-by-step</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/07/18/spring-boot-step-by-step-three-two/" rel="next" title="【第六章】一步一步学习SpringBoot2——使用过滤器Filter和监听器Listener">
                <i class="fa fa-chevron-left"></i> 【第六章】一步一步学习SpringBoot2——使用过滤器Filter和监听器Listener
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/07/19/spring-boot-step-by-step-four-two/" rel="prev" title="【番外篇】一步一步学习SpringBoot2——集成Logback日志">
                【番外篇】一步一步学习SpringBoot2——集成Logback日志 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#注意事项"><span class="nav-number">1.</span> <span class="nav-text">注意事项</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Redis简介"><span class="nav-number">2.</span> <span class="nav-text">Redis简介</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">2.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#启动Redis服务"><span class="nav-number">2.2.</span> <span class="nav-text">启动Redis服务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用Redis"><span class="nav-number">2.3.</span> <span class="nav-text">使用Redis</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#操作Redis五种数据类型"><span class="nav-number">2.4.</span> <span class="nav-text">操作Redis五种数据类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis-Client"><span class="nav-number">2.5.</span> <span class="nav-text">Redis Client</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Spring-Boot集成Redis缓存"><span class="nav-number">3.</span> <span class="nav-text">Spring Boot集成Redis缓存</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Redis缓存在Spring-Boot中使用"><span class="nav-number">4.</span> <span class="nav-text">Redis缓存在Spring Boot中使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#在监听器Listener中缓存用户数据"><span class="nav-number">4.1.</span> <span class="nav-text">在监听器Listener中缓存用户数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#更新缓存数据"><span class="nav-number">4.2.</span> <span class="nav-text">更新缓存数据</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#注解实现Redis数据缓存"><span class="nav-number">5.</span> <span class="nav-text">注解实现Redis数据缓存</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
